package com.example.demo.service.impl;

import com.example.demo.pojo.LoginUser;
import com.example.demo.pojo.ResponseResult;
import com.example.demo.pojo.User;
import com.example.demo.service.LoginService;
import com.example.demo.util.JwtUtil;
import com.example.demo.util.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class LoginServiceImpl implements LoginService {


    @Autowired
    private RedisCache redisCache;

    @Autowired
    private AuthenticationManager authenticationManager;
    @Override
    public ResponseResult<Map<String, String>> login(User user) {
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(user.getUserName(), user.getPassword());


        // 认证过滤器 进行认证
        Authentication authentication = authenticationManager.authenticate(authenticationToken);

        if (null == authentication) {
            throw new RuntimeException("登录失败");
        }


        // 内部调用UserDetailService 返回自定义的LoginUser对象
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();

        // 获取用户id
        Long userId = loginUser.getUser().getId();


        // 生成token
        String token = JwtUtil.createJWT(userId.toString());
        Map<String, String> result = new HashMap<>();
        result.put("token", token);

        // 存入redis中
        redisCache.setCacheObject("login:" + userId, loginUser);

        return new ResponseResult<>(200, "登录成功", result);
    }

    @Override
    public ResponseResult<String> logout() {
        // 从SecurityContextHolder中获取用户对象
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();

        String userId = loginUser.getUser().getId().toString();

        String redisKey = "login:" + userId;

        // 删除在redis中的key
        redisCache.deleteObject(redisKey);

        return new ResponseResult<>(200,"退出成功");
    }
}
